package com.chb.filters;

import com.chb.model.UserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author CHB
 * @createTime 2022-6-16 10:53
 */
@Component
public class JwtUtils {

    private static final String signingKey = "478ffd17-d446-48e8-8e66-c040721aa909";
    /**
     * 生成token
     * @param userInfo 用户信息
     * @author CHB
     * @date 2022-06-16 11:10:46
     * @return String
     */
    public String generateToken(UserInfo userInfo) {
        Map<String, Object> claims = new HashMap<>(4);
        claims.put("name", userInfo.getName());
        claims.put("pwd", userInfo.getPwd());
        claims.put("date", new Date());
        claims.put("phone", userInfo.getPhone());
        return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512,signingKey).compact();
    }
    /**
     * 解析token
     * @param token token
     * @author CHB
     * @date 2022-06-16 11:11:07
     * @return UserInfo
     */
    public Claims parseToken(String token){
        Claims body = null;
        try{
             body = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token).getBody();
        }catch (Exception e){
            System.out.println("解析异常");
        }
        return body;
    }

    public static void main(String[] args) {
        UserInfo userInfo = new UserInfo();
        userInfo.setName("chb");
        userInfo.setPwd("987");
        userInfo.setSex("1");
        userInfo.setPhone("1937393939");
        userInfo.setAuthorities(AuthorityUtils.createAuthorityList("admin","man"));
        JwtUtils jwtUtils = new JwtUtils();
        String s = jwtUtils.generateToken(userInfo);
        System.out.println(s);
        jwtUtils.parseToken(s);
    }
}
